package com.lifeng.zk.nativeapi.watch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.CountDownLatch;

/**
 * Created by lifeng on 2018/6/13.
 */
public class MyNodeWatch implements Watcher{
    private String zkUrl = "127.0.0.1:2181";
    //连接超时时间
    private Integer sessionOutTime = 5000;
    /** 信号量，阻塞程序执行，用于等待zookeeper连接成功，发送成功信号 */
    private CountDownLatch connectedSemaphore = new CountDownLatch(1);

    private ZooKeeper zk;

    public MyNodeWatch() throws Exception {
    }
    //收到来自Server的Watcher通知后的处理
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent == null) {
            return;
        }
        //连接状态
        Event.KeeperState state = watchedEvent.getState();
        //事件类型
        Event.EventType type = watchedEvent.getType();
        //受影响的path
        String path = watchedEvent.getPath();
        System.out.println("受影响的path:"+path);
        System.out.println("收到Watcher通知");
        System.out.println("连接状态:" + state.toString());
        System.out.println("事件类型:" + type.toString());

        if(Event.KeeperState.SyncConnected.equals(state)){
            if(Event.EventType.None.equals(type)){
                System.out.println("zk连接成功");
            }else if(Event.EventType.NodeCreated.equals(type)){
                System.out.println("节点创建");
            }else if(Event.EventType.NodeChildrenChanged.equals(type)){
                System.out.println("子节点创建");
            }else if(Event.EventType.NodeDeleted.equals(type)){
                System.out.println("节点删除");
            }
        }else if (Event.KeeperState.Disconnected.equals(state)) {
            System.out.println("与ZK服务器断开连接");
        }else if (Event.KeeperState.AuthFailed.equals(state)) {
            System.out.println("权限检查失败");
        }else if (Event.KeeperState.Expired == state) {
            System.out.println("会话失效");
        }
    }
}
